<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    #progress {
      width: 100%;
      background-color: #f3f3f3;
      margin-top: 10px;
    }

    #progress-bar {
      width: 0%;
      height: 30px;
      background-color: #4caf50;
    }
  </style>
  <title>AES File Encryption Example</title>
</head>
<body>

<h2>文件加密示例</h2>
<input type="file" id="fileInput"/>
<br><br>
<input type="password" id="passwordInput" value="123456789" placeholder="Enter password"/>
<br><br>
<button id="encryptButton">
  加密文件并保存
</button>
<button id="decryptButton">
  解密文件并保存
</button>
<br><br>
<div id="progress">
  <div id="progress-bar"></div>
</div>
<script src="../dist/bundle.min.js"></script>
<script>
  // 更新进度条
  function updateProgressBar(percentage) {
    const progressBar = document.getElementById('progress-bar');
    progressBar.style.width = percentage + '%';
  }

  let fileHeaderAes = new WeSkinnyBlobAES.FileHeaderAes();

  async function doEvent(event, name) {
    try {
      const link = document.createElement('a');
      link.href = URL.createObjectURL(await event());
      link.download = name;
      link.click();
    } catch (error) {
      console.error(error);
      alert('过程中出现错误');
      updateProgressBar(0); // 重置进度条
    }
  }

  document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('encryptButton').addEventListener('click', async () => {
      const file = document.getElementById('fileInput').files[0];
      const password = document.getElementById('passwordInput').value;
      await doEvent(
          async () => await fileHeaderAes.encrypt(file, password, (progress) => {
            updateProgressBar(progress);
          }), file.name + ".enc");
    });
    document.getElementById('decryptButton').addEventListener('click', async () => {
      const file = document.getElementById('fileInput').files[0];
      const password = document.getElementById('passwordInput').value;
      await doEvent(
          async () => await fileHeaderAes.decrypt(file, password, (progress) => {
            console.log('progress', progress)
            updateProgressBar(progress);
          }), file.name.replace(".enc", ""));
    });
  });
</script>
</body>
</html>
